(*  128 bits security pattern for domotica network.

    The routine SHL shifts all 16 bytes with a value from stack
    The basic security string must be unique for one network.

    The master commands all slaves to rotate this string to a
    specified position. This string is used to scramble the
    payload. This may be done by XORing with each byte of the
    payload. Example using the startup pattern:

    The payload data    01 02 03 04 05 06 07 08 09
    Security pattern:   11 33 55 77 99 BB DD 0F F0
    XORed payload data: 10 31 56 73 9C BD DA 07 F9
*)

create 'PATTERN
    11 c, 33 c, 55 c, 77 c, 99 c, BB c, DD c, 0F c,
    F0 c, A5 c, 5A c, D7 c, 7D c, AA c, 66 c, FF c,

create 'SECURITY  10 allot  \ Workspace

: INIT      ( -- )      'pattern 'security 10 move ;
: .KEY      ( -- )      'security 10 bounds do  i c@ .  loop ;

\ With a shift of 80 the pattern is the same again
code SHL   ( +n -- )        \ Number of bits to shift
    7F # tos bia            \ Leave only 7-bits number
    'security # moon mov
    0F # moon add           \ Start with last byte
    begin,
        #1 sr bic           \ Clear carry
        sr push             \ Prepare a run
        10 # w mov          \ All 16 bytes
        begin,
            rp )+ sr mov    \ Get previous carry result
            moon ) moon ) .b addc \ Rotate byte
            sr push         \ Save this carry
            #1 moon sub     \ Decrease pointer
            #1 w sub        \ Count all 16 bytes
        0=? until,          \ Done?
        10 # moon add       \ Yes, to last byte again
        #0 day mov          \ Empty day
        rp )+ sr mov        \ Get carry
        day day .b addc     \ To bit-0 of day
        day moon ) .b bis   \ Fix bit-0 of last byte
        #1 tos sub          \ Count shifts
    0=? until,              \ Done?
    sp )+ tos mov
    next
end-code

init    \ Show the pattern moving around
.key
8 shl
.key
8 shl
.key
4 shl
.key
4 shl
.key

\ End

